<?php
/**
 * @return
 * @author 朱乐斌
 * @date
 */

namespace app\api\controller;

use app\api\model\UserGxModel;
use app\api\validate\UserValidate;
use app\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Exception;

class User extends BaseController
{
    /**
     * private $accessKey =""1; // 你的 AccessKey
     * private $secretKey = "2"; // 你的 SecretKey
     * private $bucke = "think6";// 你在七牛云创建的空间名形
 */


    // 上传头像接口
    public function head(Request $request)
    {

        $head = $this->request->file('head');

        $extension = $head->getOriginalExtension(); // 获取文件后缀
        $path = $head->getPathname();
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey ="七牛云的accessKey";
        $secretKey = "七牛云的secretKey";
        $bucket = "名称";
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 要上传文件的本地路径
        $filePath = $path;
        // 上传到存储后保存的文件名
        $key = uniqid().time().'.'.$extension;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的  putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath, null, 'application/octet-stream', true, null, 'v2');
        $data = [
            'url' => 'http://s2mgl5zzu.bkt.clouddn.com/'.$key,
        ];
        $user = UserGxModel::where('phone',$request->phone)->find();
        $userdate = [
            'image' => $data['url'],
        ];
        $user = $user->save($userdate);
        if($user) $this->success('上传成功');
    }



    // 获取个人信息接口
    public function user(Request $request)
    {
        // 使用登录的token解析手机号，查询用户信息
        $phone = $request->phone;
        try {
            $user = new UserGxModel();
            $user = $user->where('phone',$phone)->withoutField('create_time,update_time,delete_time,password,sort,state')->find();
            $this->success($user);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    // 修改个人信息
    public function userEdit(Request $request)
    {
        // 接收修改数据
        $date = $this->request->post();
        try {
            // 验证数据是否正确
            validate(UserValidate::class)->scene('user')->check($date);
            // 修改数据，使用手机号查询出修改信息的用户
            $user = new UserGxModel();
            $user = $user->where('phone',$request->phone)->find();
            if (isset($date['name'])) $user->name = $date['name'];
            if (isset($date['sex'])) $user->sex = $date['sex'];
            if (isset($date['image'])) $user->image = $date['image'];
            if (isset($date['content'])) $user->name = $date['content'];
            if (isset($date['age'])) $user->name = $date['age'];
            if ($user->save($date)) $this->success('存储成功');
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }


}